package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.pojo.ManageProject;
import com.itheima.pojo.Project;
import com.itheima.service.ManageProjectService;
import com.itheima.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ManageProjectService manageProjectService;

    /**
     * 分页查询
     * @param map
     * @return
     */
    @GetMapping("/page")
    public R<Page<Project>> page(@RequestParam Map<String,String> map){

        String currentPage = map.get("currentPage");
        String pageSize = map.get("pageSize");
        String queryString = map.get("queryString");
        if ("null".equals(queryString)){
            queryString = null;
        }

        Page<Project> projectPage = new Page<>(Integer.parseInt(currentPage),Integer.parseInt(pageSize));

        LambdaQueryWrapper<Project> plqw = new LambdaQueryWrapper<>();
        plqw.like(queryString != null,Project::getCode,queryString).or().like(queryString != null,Project::getName,queryString);

        projectService.page(projectPage,plqw);
        return R.success(projectPage);

    }

    /**
     * 新增
     * @param project
     * @return
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody Project project){
        projectService.save(project);
        return R.success("新建成功");
    }

    /**
     * 修改
     * @param project
     * @return
     */
    @PutMapping("/update")
    public R<String> update(@RequestBody Project project){
        projectService.updateById(project);
        return R.success("修改成功");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R<String> deleteById(@PathVariable long id){

        LambdaQueryWrapper<ManageProject> mplqw = new LambdaQueryWrapper<>();
        mplqw.eq(ManageProject::getProjectId,id);
        int count = manageProjectService.count(mplqw);

        if (count > 0){
            throw new CustomException("该项与其他检查组有关联,无法删除");
        }
        projectService.removeById(id);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<Project>> list(){
        List<Project> projects = projectService.list();
        return R.success(projects);
    }
}
